Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1
1.1 Machine Language A computer programming language which has binary instructions those are executed directly by a computer. Machine Language programming was very slow and difficult to understand for most of the programmers. 2
1.2 Assembly Language Assembly language is a low level programming language which implements a symbolic representation of the machine codes. Assembly language is converted into executable machine code by a utility program called assembler. 3
1.3 High level Language A machine independent programming language which contains English words and commonly used mathematical notations. Programs written in a high-level language must be translated into machine language by a compiler. Compiler is a software that translates a program written in a high-level programming language (C/C++, COBOL, etc.) into machine language. Examples: C++, Java and FORTRAN etc 4
1.4 History of C and C++ C++ was developed by Bjarne Stroustrup in the early 1980s at Bell Labs. C++ is an extension of C programming language and provides capabilities for Object-Oriented Programming (OOP). 5
1.5 Introduction to Programming Preprocessor directives : #include<iostream> main() Function 1. Body of the function 2. Other statements 3. Return statement Comments: //, /*. */ 6
1.5.1 Preprocessor Directives Preprocessor directives Processed by preprocessor before compiling Begin with #(hash) Example: #include <iostream> /*Tells preprocessor to include the input/output stream header file <iostream> */ White spaces Blank lines, space characters and tabs Delimiter, used to make programs easier to read Extra spaces are ignored by the compiler 7
1.5.2 main() Function A part of every C++ program Only one function in a program must be main() Keyword : A word in code that is reserved by C++ for a specific use. Ex: int, char, if, else, for, while, break, return, namespace etc Header of main() function : int/void main( ) Body of main() is delimited by braces { } 8
1.5.3 Comments Explain programs to other programmers. Improve program readability Ignored by compiler Types of comment: Single-line comment Begin with // Example: int main() Multi-line comment Start with /* //this is main() function End with */ 9
1.5.4 Statements Instruct the program to perform an action. Every statement must end with a semicolon (;) Examples : int x; cin>>x; cout << Welcome to C++ ; return 0; 10
1.5.5 Variable & Data types Variable: Location in memory where value can be stored ex. int x, float y etc Fundamental data types: int integer numbers : 1, 2, 4,. char characters : a, c, float, double floating point numbers: 2.5, 4.96 The value of a variable could be changed while the program is running. 11
1.5.6 Input statement cin >> x; cin /std::cin // x is a variable Standard input stream object. Defined in input/output stream header file <iostream> We are using a name (cin/cout) that belongs to namespace std. Stream extraction operator >> Value from left (operand) inserted into right operand (variable). 12
1.5.7 Output statement cout << Welcome to C++ ; cout /std::cout Standard output stream object. Defined in input/output stream header file <iostream> We are using a name (cout/cin) that belongs to namespace std. Stream insertion operator << Value to right (right operand) inserted into left operand. The string of characters contained between after the operator << shows on computer screen. 13
1.5.8 return Statement Terminates the execution of a function and returns control to the calling function. used at the end of function The value 0 indicates the program terminated successfully. Example return 0; / return(0); 14
2.1 First program in C++ #include<iostream> #include<conio.h> using namespace std; int main( ) { cout<< Welcome to C++\n ; getch (); } return 0; 15
2.2 Escape Sequence Escape character: backslash : "\" Escape sequence: A character preceded by backslash (\) Examples : "\n : Newline. Cursor moves to beginning of next line on the screen \t : Horizontal tab. Move the screen cursor to the next tab stop. \b : Backspace. Move the screen cursor one space back etc 16
2.2.1 Modifying First C++ Program Print text on one line using multiple statements. Each stream insertion (<<) resumes printing where the previous one stopped. Example statements: cout << Welcome ; cout << to C++\n ; 17
2.2.2 Modifying First C++ Program Print text on several lines using a single statement. Each newline escape sequence positions the cursor to the beginning of the next line. Two newline characters back to back outputs a blank line. Example statement : cout << Welcome\n to\n\nc++\n ; 18
2.3 Adding Integers #include<iostream> #include<conio.h> void main( ) { } int a, b, sum; cout<< Enter value of a : ; cin>>a; cout>> Enter value of b : ; cin>>b; sum = a + b; cout<< Value of a and b : <<sum; getch (); 19
3.1 Memory Concepts A variable is a memory location in C++ Programming language Every variable has name, type, size and value. A name like number1, number2 and sum that refer to a value is called variable. Example: sum = number1 + number2; Value of sum is overwritten Values of number1 and number2 remain intact 20
3.1.1 Example Memory locations after storing values for number1 and number2. 21
3.1.2 Continued Memory locations after calculating and storing the sum of number1 and number2. 22
3.2 Arithmetic Arithmetic operators are the binary operators that takes two input to perform calculation. Examples: Addition (+) Subtraction (-) Multiplication (*) Division (/) Modulus(%) 23
3.2.1 Arithmetic operators C++ operation C++ arithmetic operator Algebraic expression Addition + f + 7 f + 7 Subtraction - p c p - c Multiplication * bm or b m b * m Division / x / y or x y or x y x / y C++ expression Modulus % r mod s r % s 24
Example Division (/) / : Integer division truncates remainder 7 / 5 evaluates to 1 Modulus(%) % : Modulus operator returns remainder 7 % 5 evaluates to 2 25
3.3 Rules of operator precedence 1) Operators in parentheses evaluated first 2) Multiplication, division, modulus applied next 3) Addition, subtraction applied last 26
3.3.1 Precedence of Arithmetic Operators Operator(s) Operation(s) Order of evaluation (precedence) ( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right. * Multiplication / % Division Modulus Evaluated second. If there are several, they are evaluated left to right. + - Addition Subtraction Evaluated last. If there are several, they are evaluated left to right. 27
3.4 Decision making : Relational and Equality Operators Relational Operator C++ operator Sample C++ condition Meaning of C++ condition Relational Operator ( 4 operators) > X >y X is greater than y < X < y X is less than y > >= X >= y X is greater than or equal to y < <= X <= y X is less than or equal to y Equality Operator ( 2 operators) == X == y X is equal to y!= X!= y X is not equal to y 28
Example: comparing integer using if statement, relational operator and equality operator void main() { int x,y; cout<< enter two numbers ; cin>>x>>y; if(x==y) cout<<x<< is equal to <<y; if(x!=y) cout<<x<< is not equal to <<y; if(x<y) if(x>y) cout<<x<< is smaller than <<y; cout<<x<< is greater than <<y; } 29
4.1 Control Statement: Introduction Program control specify the order in which statements execute in a program. C++ provides many building blocks to specify the order of execution. Some of them are : 1. If Statement 2. if else Statement 3. while Statement 30
4.2 Algorithm A procedure for solving a problem in terms of 1. The action to execute 2. The order in which the actions execute is called an algorithm. 31
4.3 Pseudo code Pseudo code is an artificial and informal language that helps us to implement algorithms without having to worry about the strict details of C++ language syntax. Pseudo code does not execute on computer. 32
4.3.1 Pseudo code example Example: Sum of two numbers. 1 Prompt the user to enter the first integer 2 Input the first integer 3 Prompt the user to enter the second integer 4 Input the second integer 5 Add first integer and second integer, store result 6 Display result 33
5.1 Control Structure Statements used to control the flow of execution in a program. There are three control structures: 1. Sequence Structure 2. Selection Structure 3. Repetition Structure 34
5.1.1 Sequence Structure In Sequence Structure, the execution of C++ statements is done one after another in an order in which they are written. 35
5.1.2 Selection Structure Selection Structure selects which statement will execute on the basis of given conditions. C++ provides three types of selection structures: 1. if( ) 2. if else( ) 3. switch( ) 36
5.1.2.1 Selection Structure a) if() : if() selection statement either performs an action if a condition is true or skips the action if the condition is false. Example: if(grade>=60) cout << passed ; 37
5.1.2.2 Selection Structure b) if else() : If else() selection statement performs an action if a condition is true or performs a different action if the condition is false. Example: if(grade>=60) cout << passed ; else cout << fail ; 38
Nested if...else Statements Nested if else statement test for multiple cases by placing if...else selection statements inside other if...else selection statements. 39
Nested if...else example Example: if ( studentgrade >= 90 ) cout << "A"; else if ( studentgrade >= 80 ) cout << "B"; else if ( studentgrade >= 70 ) cout << "C"; else if ( studentgrade >= 60 ) cout << "D"; else cout << "F"; 40
5.1.2.3 Selection Structure c) switch() : switch() selection statement performs one of the many different actions, depending on the value of an integer expression. 41
Conditional Operator? : The conditional operator is ternary operator it takes three operands. The operands, together with the conditional operator, form a conditional expression. 1. The first operand is a condition, 2. The second operand is the value for the entire conditional expression if the condition is true 3. The third operand is the value if the condition is false. Example: cout << ( grade >= 60? "Passed" : "Failed" ); 42
Block A group of statements enclosed within a pair of braces { } is called a Block. for example: { } statement1; statement2; statement3; 43
5.1.3 Repetition Structure Looping statements that enable programs to perform statements repeatedly as long as a condition remains true. C++ provides three types of repetition statements : 1. while() 2. for() 3. do while() 44
6.1 while () Repetition Statement A repetition statement allows the programmer to specify that a program should repeat an action while some condition remains true. 45
6.1.1 Example void main() { int product = 3; while ( product <= 100) product = 3 * product; } 46
6.2 Formulating Algorithms: Counter-Controlled Repetition Counter-controlled repetition is often called definite repetition because the number of repetitions is known before the loop begins executing. 47
6.2.1 Example #include <iostream> #include <conio.h> using namespace std; int main() { int counter = 1; while ( counter <= 10 ) { cout << counter << endl; counter++; } } getch(); return 0; 48
6.3 Formulating Algorithms: Sentinel-Controlled Repetition Sentinel-controlled repetition is often called indefinite repetition because the number of repetitions is not known before the loop begins executing. 49
6.3.1 Example #include <iostream> using namespace std; void main() { int score, sum; sum = 0; cout << "Enter score (-1 to quit): "; cin >> score; while (score!= -1) { sum += score; cout << "Enter score (-1 to quit): "; cin >> score; } cout << "Sum = " << sum << endl; } 50
7.1 Nested Control Statement The only other structured way control statements can be connected, namely, by nesting one control statement within another. A control command placed inside another control command is said to be nested. 51
7.1.1 Example #include<iostream> using namespace std; void main() { int passes = 0, failures=0, studentcounter = 1, ; int result; // one exam result (1 = pass, 2 = fail) while ( studentcounter <= 10 ) { cout << "Enter result (1 = pass, 2 = fail): "; cin >> result; if ( result == 1 ) //if else nested in while passes = passes + 1; else failures = failures + 1; studentcounter = studentcounter + 1; } } 52
7.2 Assignment Operators C++ provides several assignment operators for abbreviating assignment expressions. = is an assignment operator, which assigns the value of its right operand to its left operand. Example: c=c+3; c+=3; [Variable = variable operator expression] [Variable operator= expression] 53
7.2.1 Assignment Operators Assignment operator Sample expression Explanation += c += 7 c = c + 7 -= d -= 4 d = d -4 *= e *=5 e = e * 5 /= f /= 3 f = f / 3 %= g %= 9 g = g % 9 54
7.3 Increment and decrement operators C++ provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric variable. Example: 1. ++ Unary increment operator 2. -- Unary decrement operator 55
7.3.1 Increment and decrement operators Operator Called Sample expression Explanation ++ Preincrement ++a Increment a by 1, then use new value of a in the expression in which a resides. ++ Postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1. -- Predecrement --b Decrement b by 1, then use new value of b in the expression in which b resides. -- Postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1. 56
8.1 Essentials of Counter- Controlled Repetition Counter-controlled repetition requires: 1. The name of a control variable (or loop counter) 2. The initial value of the control variable 3. The loop-continuation condition that tests for the final value of the control variable. 4. The increment (or decrement) by which the control variable is modified each time through the loop. 57
8.1 Example #include <iostream> void main() { int counter=1; while ( counter<=10) { cout << counter << " "; counter ++; } } Output of the above Example: 1 2 3 4 5 6 7 8 9 10 58
8.2 for() Repetition Statement for( ; ; ) repetition statement specifies the counter-controlled repetition details in a single line of code: for statement header components 59
8.2.1 Example #include <iostream> using namespace std; int main( ) { for (int counter=1; counter<=10; counter++) cout<<counter<<" "; return 0; } Output of the above Example: 1 2 3 4 5 6 7 8 9 10 60
8.3 Examples using the for statement Vary the control variable from 1 to 10 in increments of 1. for ( int i = 1; i <= 10; i++ ) Vary the control variable from 10 down to 1 in increments of -1 (that is, decrements of 1). for ( int i = 10; i >= 1; i-- ) Vary the control variable from 7 to 77 in steps of 7. for ( int i = 7; i <= 77; i += 7 ) Vary the control variable from 20 down to 2 in steps of -2. for ( int i = 20; i >= 2; i -= 2 ) 61
9.1 do...while() Repetition Statement The do...while() repetition statement is similar to the while statement. The do...while() statement tests the loopcontinuation condition after the loop body executes; therefore, the loop body always executes at least once. 62
9.2 Example #include <iostream> using namespace std; int main() { int counter=1; do { cout<<counter<< ; counter++; } while (counter<=10); return 0; } 63
9.3 Switch Multiple- Selection Statement C++ provides the switch multiple-selection statement to perform many different actions based on the possible values of a variable or expression. Example: switch(day) { } case 1: cout<< Saturday ; break; 64
9.3.1 Example #include <iostream> void main() { int day; cout<< enter the day ; cin>>day; switch(day) { case 1: cout<< Sunday ; break; 65
9.3.1 Example continued case 2: cout<< Monday ; break; case 3: cout<< Tuesday ; break; case 4: cout<< Wednesday ; break; default: cout<< incorrect entry ; break; } } 66
10.1 Break statement The break statement, when executed in a while, for, do while, or switch control statement, causes immediate exit from that control statement. 67
10.1.1 Example for (count=1; count<=10; count++) { if(count == 5) break; //break loop if x is 5 cout<<count<< ; } cout<< \n Broke out of the loop of count = <<count; 68
10.2 Continue statement The continue statement, when executed in a while, for or do while statement, skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop. 69
10.2.1 Example for (count=1; count<=10; count++) { if(count == 5) continue; //Skips remaining code on loop cout<<count<< ; } 70
10.3 Logical operators C++ provides logical operators that are used to form more complex condition by combining simple conditions. The logical operators are: 1. && Logical AND 2. Logical OR 3.! Logical NOT 71
10.3.1 Logical AND(&&) operator Logical AND(&&) operator is used when we wish to ensure that two conditions are both true before we choose a certain path of execution. Example: if(gender== F && age>=65) seniorfemales++; 72
10.3.1.1 Logical AND(&&) operator Expression 1 Expression 2 Expression 1 && Expression 2 False False False False True False True False False True True True 73
10.3.2 Logical OR ( ) operator Logical OR ( ) operator is used when we wish to ensure at some point in a program that either or both of two conditions are true before we choose a certain path of execution. Example: if((semesteraverage>=90) (finalexam>=90)) cout<< Student grade is A ; 74
10.3.2.1 Logical OR ( ) operator Expression 1 Expression 2 Expression 1 && Expression 2 False False False False True True True False True True True True 75
10.3.3 logical negation (!) operator C++ provides the! (logical NOT) operator to enable a programmer to reverse the meaning of a condition. Unlike the && and binary operators, which combine two conditions, the unary logical negation operator has only a single condition as an operand. Ex. if(!(grade<= 59)) cout<< You have passed the examination ; Expression False True! Expression True Fasle 76
10.4 Confusing the Equality (==) and Assignment (=) operators Example: if( paycode == 4) cout<< You get a bonus ; but accidentally wrote if(paycode = 4) count<< You get a bonus ; 77
11.1 Derived Data Types Data types that are derived from fundamental data types are known as derived data types. Derived data types don't create a new data type; instead, they add some functionality to the basic data types. Ex. Two derived data type are - Array & Pointer. 78
11.2 Array An array is a sequenced collection of elements of the same data type, placed in contiguous memory locations that are referred to by the same name. Each element of an array can be accessed by a subscript value which indicates the position of an element in an array. 79
11.2.1 Array declaration An array can be declared as: int num[ ] = {2,8,7,6,0}; Array size(length) = UB LB + 1 We need an array to store large number of variables of same type under a single variable. Ex. To store Marks of 50 students 80
11.2.2 Example #include<iostream> #include<conio.h> using namespace std; int A [ ] = {16, 2, 77, 40, 120}; int n, result=0; void main () { for ( n=0 ; n<5 ; n++ ) { result += A[n]; } cout << result; getch(); } 81
12.1 Function A function is a collection of statements which contains data definitions and code that performs a specific task - a single, well-defined task. Advantage using function: This makes programs easier to read and maintain. Statements in function bodies are written only once Reused from perhaps several locations in a program Hidden from other functions Avoid repeating code 82
12.2 Function Prototype Function prototype also called function declaration The general form of a function prototype is: data-type function_name (type 1 arg 1, type 2 arg 2); Where, data-type represents the data-type of the item that is returned by the function, function_name represents the function name, and type 1, type 2,, type n represents the data-type of the arguments arg 1, arg 2,, arg n. Example: int addtwonumbers(int, float); 83
12.3 Function definition Definition of a function: Header : Return type, Function Name, Parameter(s) [type and name pair ]. Body : a collection of statements. Example: int addtwonumbers (int numberone, float numbertwo ) { int sum; sum = numberone + numbertwo; return sum; } 84
12.4 Return Type The return type is the data type of the result returned to the caller function. Example: int addtwonumbers (int numberone, float numbertwo ) { int sum; sum = numberone + numbertwo; return sum; } 85
12.5 Function Call There are two main ways for calling a function: 1. Call by value 2. Call by reference 86
12.1.1 Example #include<iostream> int square(int y) { int p; p=y*y; return p; } void main() { int i; i=10; cout<<square(i); } 87